<template>
  <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
    <el-form-item label="姓名" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="昵称" prop="username">
      <el-input v-model="ruleForm.username"></el-input>
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio label="男" border></el-radio>
        <el-radio label="女" border></el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item label="校验密码" prop="checkPass">
      <el-input
          v-model="ruleForm.checkPass"
          type="password"
          autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item label="生日">
      <div class="block">
        <el-date-picker
            v-model="ruleForm.birth"
            type="date"
            placeholder="选择一天"
            :disabled-date="disabledDate"
            :shortcuts="shortcuts"
        >
        </el-date-picker>
      </div>
    </el-form-item>
    <el-form-item label="学历">
      <el-select v-model="ruleForm.degree" placeholder="学历">
        <el-option
            v-for="item in degree"
            :key="item"
            :label="item"
            :value="item"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="住址">
      <el-input v-model="ruleForm.address"></el-input>
    </el-form-item>
    <el-form-item label="入职日期">
      <div class="block">
        <el-date-picker
            v-model="ruleForm.entryDate"
            type="date"
            placeholder="选择一天"
            :disabled-date="disabledDate"
            :shortcuts="shortcuts"
        >
        </el-date-picker>
      </div>
    </el-form-item>
    <el-form-item label="电话号码" prop="phoneNumber">
      <el-input v-model="ruleForm.phoneNumber"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="ins()">确认</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {reactive, toRefs} from 'vue'
import {ElMessage} from "element-plus";
import {findUser, getUserList, saveUser, upInfo} from "@/utils/api";

export default {
  name: "Ter_re_Form",

  setup() {
    const state = reactive({
      disabledDate(time) {
        return time.getTime() > Date.now()
      },
      shortcuts: [
        {
          text: '今天',
          value: new Date(),
        },
        {
          text: '昨天',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date
          },
        },
        {
          text: '一星期前',
          value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            return date
          },
        },
      ],
    })

    return {
      ...toRefs(state),
      degree: ["无","小学","中学","专科","本科","研究生","硕士","博士","博士后"]
    }
  },

  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validator = (rule, value, callback) => {
      if (/^1[345789]\d{9}$/.test(value) == false) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {},
      form: {},
      rules: {
        name: [{required: true, message: '名字不能为空', trigger: 'blur' }],
        username: [{required: true, message: '昵称不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          {min: 6, max: 20, message: '密码长度6-20字符', trigger: 'blur'}
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur', required: true }
        ],
        phoneNumber: [
          {required: true, message: "请输入手机号码", trigger: "blur"},
          { validator: validator, trigger: 'blur', required: true },
        ],
      },
    }
  },
  created() {
    // 从session中获取标识，判断是否为编辑状态
    if (sessionStorage.getItem("3") === "edit"){
      // 若用户身份是教师，则渲染信息上表单
      if(sessionStorage.getItem("2") === "教师"){
        this.session1 = JSON.parse(sessionStorage.getItem("1"))
        this.finddd()
      }
    }
  },
  methods: {
    // 将表单数据插入数据库
    ins() {
      // 判断是否已登陆
      if (sessionStorage.getItem("1") === null){
        // 未登陆则将信息插入数据库
        this.inster()
      }else {
        // 已登陆则将信息更新入数据库
        this.updata()
      }
    },
    //清空
    resetForm() {
      this.ruleForm = {}
    },

    // 根据某个值查询信息并渲染上表单
    finddd() {
      this.ruleForm = this.session1
      sessionStorage.removeItem("3")
    },
    // 更新个人信息
    updata(){
      // 因为用户输入的表单内没有id，所有要从session里取
      this.ruleForm.id = this.session1.id
      // 将用户信息传至后台更新数据库
      upInfo("ter", this.ruleForm).then(res => {
        switch (res.code){
          case "0":
            // 将用户信息写入session中
            sessionStorage.setItem("1", JSON.stringify(this.ruleForm))
            // 清空表单
            this.ruleForm = {}
            ElMessage.success("更新成功！")
            setTimeout(()=>{
              // 0.5秒后刷新并跳转到main页面
              this.$router.push({path:"/main"})
            },500)
                break;
          case "1":
            ElMessage.error("更新失败！")
        }
      })

    },
    // 插入注册
    inster(){
      var fname = this.ruleForm.name //记录表单接收的名字和密码
      var fpass = this.ruleForm.password
      // 判断该用户是否已存在
      findUser("ter",fname, fpass).then(res => {
        if(res.code === "0"){
          ElMessage.error("该用户已存在！")
        }
        else {
          saveUser("ter",this.ruleForm).then(res => {
            this.ruleForm.id = res.data
          })
          // 将用户信息和角色写入session
          sessionStorage.setItem("1", JSON.stringify(this.ruleForm))
          sessionStorage.setItem("2","教师")
          // 清空表单
          this.ruleForm = {}
          ElMessage.success("注册成功！")
          setTimeout(()=>{
            // 刷新跳转到main页面
            this.$router.push({path:"/main"})
          },500)
        }
      })
    }
  },
}
</script>

<style scoped>

.demo-ruleForm {
  width: 50%;
  margin: 0 auto;
}

</style>